<script setup lang="ts">
import { ref, computed, onMounted, watch } from 'vue';
import { useAppStore } from '@/store';
import { useThemeStore } from '@/store/modules/theme';
import { ElCard, ElAvatar, ElDescriptions, ElDescriptionsItem, ElTag, ElDivider, ElButton, ElUpload, ElMessage, ElDialog } from 'element-plus';
import { Edit, UploadFilled, Plus } from '@element-plus/icons-vue';
import { $t } from '@/locales';
import { userGenderRecord, enableStatusRecord } from '@/constants/business';
import { useAuthStore } from '@/store/modules/auth';
import manage from "@/views/function/material/Image/index.vue";

const appStore = useAppStore();
const themeStore = useThemeStore();
const authStore = useAuthStore();

const userInfo = computed(() => authStore.userInfo);

// For avatar upload
const avatarUrl = computed(() => userInfo.value.userImages || 'http://127.0.0.1:9000/image-bucket/20250514/fbee6c07a7d24746884456b56b6a21bfd1ee7e8c-5af4-462a-bf59-e58a053dba21.jpg');
const uploading = ref(false);
const uploadRef = ref(null);

// Material uploader dialog
const showMaterialUploader = ref(false);
const showUploadPanel = ref(false);
const selectedImage = ref('');

// Show upload dialog
const showUploadDialog = () => {
  if (uploadRef.value) {
    uploadRef.value.openDialog(1, 'single');
  }
};

// Watch for changes to the upload component reference
onMounted(() => {
  if (uploadRef.value) {
    // Initialize with a watch to detect changes
    watch(() => uploadRef.value.singleImage, (newValue) => {
      if (newValue) {
        handleAvatarChange();
      }
    });
  }
});

// Watch for changes to the single image in the upload component
const handleAvatarChange = async () => {
  if (uploadRef.value && uploadRef.value.singleImage) {
    // Update the user avatar in auth store
    authStore.userInfo.userImages = uploadRef.value.singleImage;
    
    // Here you would typically call an API to update the user avatar
    // For example: await updateUserAvatar(uploadRef.value.singleImage);
    
    ElMessage.success($t('page.userCenter.avatarUploadSuccess'));
  }
};

// Example user stats
const userStats = [
  { label: $t('page.userCenter.loginCount'), value: '128' },
  { label: $t('page.userCenter.lastLogin'), value: new Date().toLocaleString() },
  { label: $t('page.userCenter.registerDate'), value: '2024-01-01' },
];

const recentActivities = [
  { date: '2024-05-14', action: $t('page.userCenter.activity.login'), time: '15:30' },
  { date: '2024-05-13', action: $t('page.userCenter.activity.updateProfile'), time: '09:45' },
  { date: '2024-05-10', action: $t('page.userCenter.activity.changePassword'), time: '11:20' },
];

// Handle selecting a material image
function selectMaterialImage(url: string) {
  selectedImage.value = url;
  showUploadPanel.value = false;
}

// Apply the selected image as avatar
function applySelectedImage() {
  if (selectedImage.value) {
    authStore.userInfo.userImages = selectedImage.value;
    showMaterialUploader.value = false;
    selectedImage.value = '';
    ElMessage.success($t('page.userCenter.avatarUploadSuccess'));
  }
}
</script>

<template>
  <div class="user-center-container p-20px">
    <div class="user-center-header flex gap-24px flex-wrap">
      <!-- User Avatar and Basic Info Card -->
      <ElCard class="flex-1 min-w-300px" :body-style="{ padding: '20px' }">
        <div class="flex items-start gap-20px flex-wrap md:flex-nowrap">
          <div class="avatar-container relative">
            <ElAvatar :size="100" :src="avatarUrl" />
            <div class="avatar-upload">
              <ElButton 
                type="primary" 
                circle 
                size="small" 
                class="upload-button" 
                :icon="Edit" 
                @click="showMaterialUploader = true"
              />
            </div>
          </div>
          <div class="user-info flex-1">
            <h2 class="text-xl font-semibold mb-8px">{{ userInfo.userName || 'Admin User' }}</h2>
            <p class="text-gray opacity-80 mb-12px">{{ userInfo.nickName || 'System Administrator' }}</p>
            
            <div class="flex flex-wrap gap-8px mt-16px">
              <ElTag 
                v-for="role in userInfo.roles" 
                :key="role" 
                :type="themeStore.themeColor.primary"
                effect="light"
              >
                {{ role }}
              </ElTag>
            </div>
            
            <div class="user-stats flex gap-16px mt-16px">
              <div v-for="(stat, index) in userStats" :key="index" class="stat-item text-center">
                <div class="stat-value font-semibold">{{ stat.value }}</div>
                <div class="stat-label text-xs opacity-70">{{ stat.label }}</div>
              </div>
            </div>
          </div>
        </div>
      </ElCard>

      <!-- User Details Card -->
      <ElCard class="flex-1 min-w-300px mt-0 md:mt-0" :body-style="{ padding: '20px' }">
        <template #header>
          <div class="flex justify-between items-center">
            <h3 class="m-0">{{ $t('page.userCenter.contactInfo') }}</h3>
            <ElButton type="primary" plain size="small" :icon="Edit">
              {{ $t('common.edit') }}
            </ElButton>
          </div>
        </template>
        
        <ElDescriptions :column="1" border>
          <ElDescriptionsItem :label="$t('page.manage.user.userPhone')">
            {{ userInfo.userPhone || '未设置' }}
          </ElDescriptionsItem>
          <ElDescriptionsItem :label="$t('page.manage.user.userEmail')">
            {{ userInfo.userEmail || '未设置' }}
          </ElDescriptionsItem>
          <ElDescriptionsItem :label="$t('page.manage.user.userGender')">
            <ElTag v-if="userInfo.userGender" type="primary">
              {{ $t(userGenderRecord[userInfo.userGender]) }}
            </ElTag>
            <span v-else>未设置</span>
          </ElDescriptionsItem>
          <ElDescriptionsItem :label="$t('page.manage.user.userStatus')">
            <ElTag v-if="userInfo.status" :type="userInfo.status === 1 ? 'success' : 'warning'">
              {{ $t(enableStatusRecord[userInfo.status]) }}
            </ElTag>
            <span v-else>未设置</span>
          </ElDescriptionsItem>
        </ElDescriptions>
      </ElCard>
    </div>

    <!-- Recent Activity Card -->
    <ElCard class="mt-24px">
      <template #header>
        <div class="card-header">
          <h3 class="m-0">{{ $t('page.userCenter.recentActivity') }}</h3>
        </div>
      </template>
      
      <div class="timeline">
        <div v-for="(activity, index) in recentActivities" :key="index" class="timeline-item">
          <div class="timeline-dot" :style="{ 'background-color': themeStore.themeColor.primary }"></div>
          <div class="timeline-content">
            <div class="flex justify-between">
              <div class="activity-action">{{ activity.action }}</div>
              <div class="activity-time text-sm opacity-60">{{ activity.time }}</div>
            </div>
            <div class="activity-date text-sm opacity-70">{{ activity.date }}</div>
          </div>
        </div>
      </div>
    </ElCard>
    
    <!-- Material Uploader Dialog -->
    <ElDialog v-model="showMaterialUploader" title="选择头像" width="800px" destroy-on-close>
      <div class="material-uploader">
        <div v-if="selectedImage" class="selected-image-preview">
          <img :src="selectedImage" alt="Selected Avatar" style="max-width: 200px; max-height: 200px; margin-bottom: 15px;">
          <ElButton type="primary" @click="applySelectedImage">{{ $t('common.confirm') }}</ElButton>
        </div>
        <div v-else>
          <div style="text-align: center; margin-bottom: 20px;">
            <div 
              @click="showUploadPanel = !showUploadPanel"
              style="cursor: pointer; border: 1px dashed #dcdfe6; border-radius: 4px; height: 120px; display: flex; align-items: center; justify-content: center; margin-bottom: 10px;"
            >
              <div style="text-align: center; color: #909399;">
                <el-icon style="font-size: 28px; margin-bottom: 8px;"><Plus /></el-icon>
                <div>点击上传</div>
              </div>
            </div>
          </div>
          
          <div v-if="showUploadPanel" class="upload-panel">
            <!-- Image Galleries from Material Module -->
            <manage flag="1" @selectImage="selectMaterialImage" />
          </div>
        </div>
      </div>
    </ElDialog>
  </div>
</template>

<style scoped lang="scss">
.user-center-container {
  max-width: 1200px;
  margin: 0 auto;
}

.avatar-container {
  position: relative;
  display: inline-block;
}

.avatar-upload {
  position: absolute;
  right: 0;
  bottom: 0;
}

.upload-button {
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.timeline {
  position: relative;
  padding-left: 20px;
}

.timeline-item {
  position: relative;
  padding-bottom: 20px;
  padding-left: 20px;
}

.timeline-item:last-child {
  padding-bottom: 0;
}

.timeline-dot {
  position: absolute;
  left: -5px;
  top: 5px;
  width: 10px;
  height: 10px;
  border-radius: 50%;
  background-color: v-bind('themeStore.themeColor.primary');
}

.timeline-item:not(:last-child)::before {
  content: '';
  position: absolute;
  left: 0;
  top: 15px;
  height: calc(100% - 15px);
  width: 1px;
  background-color: #e0e0e0;
}

.activity-date {
  margin-top: 4px;
}

.material-uploader {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.selected-image-preview {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-bottom: 20px;
}

.hidden {
  display: none;
}

/* Dark mode adjustments */
:deep(.dark .timeline-item:not(:last-child)::before) {
  background-color: #4a4a4a;
}
</style>
